<template>
    <div class="container-main">
        <div class="header-container">
            <div class="header-button">
                <el-row>
                    <el-button :class="{ active: isVisitorActive }" @click="showVisitorData">游客用户</el-button>
                    <el-button :class="{ active: isAdminActive }" @click="showAdminData">管理员用户</el-button>
                </el-row>
            </div>
            <div class="header-search">
                <el-button class="search-button" type="primary" @click="addDialogFormVisible = true">新增用户</el-button>
                <el-input class="search-input" placeholder="请输入用户名称" v-model="searchKeyword" clearable>
                </el-input>
                <el-button type="primary" @click="searchUsers">搜索</el-button>
            </div>
        </div>
        <div>
            <el-table :data="paginatedTableData" border style="width: 100%">
                <el-table-column prop="id" label="用户ID" width="auto">
                </el-table-column>
                <el-table-column prop="name" label="用户姓名" width="auto">
                </el-table-column>
                <el-table-column prop="account" label="登录账号" width="auto">
                </el-table-column>
                <el-table-column prop="contact" label="联系方式" width="auto">
                </el-table-column>
                <el-table-column prop="date" label="录入时间" width="auto">
                </el-table-column>
                <el-table-column label="操作" width="auto" flex="1">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" @click="editUser(scope.row)">修改</el-button>
                        <el-button type="text" size="small" @click="deleteUser(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <div style="display: flex;justify-content: center;">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="currentPage" :page-sizes="[5, 10, 15, 20]" :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="filteredTableData.length">
                </el-pagination>
            </div>
        </div>
        <!-- 新增用户 -->
        <el-dialog title="新增用户" :visible.sync="addDialogFormVisible">
            <el-form :model="addForm">
                <el-form-item label="用户姓名" :label-width="formLabelWidth">
                    <el-input v-model="addForm.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="登录账号" :label-width="formLabelWidth">
                    <el-input v-model="addForm.account" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="登录密码" :label-width="formLabelWidth">
                    <el-input v-model="addForm.password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="联系方式" :label-width="formLabelWidth">
                    <el-input v-model="addForm.contact" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelAddUser">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 修改用户 -->
        <el-dialog title="修改用户" :visible.sync="editDialogFormVisible">
            <el-form :model="editForm">
                <el-form-item label="姓名" :label-width="formLabelWidth">
                    <el-input v-model="editForm.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="登录账号" :label-width="formLabelWidth">
                    <el-input v-model="editForm.account" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="登录密码" :label-width="formLabelWidth">
                    <el-input v-model="editForm.password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="联系方式" :label-width="formLabelWidth">
                    <el-input v-model="editForm.contact" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editDialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEditUser">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 删除确认对话框 -->
        <el-dialog title="提示" :visible.sync="deleteConfirmDialogVisible" width="30%">
            <span>确定要删除该用户吗？</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="deleteConfirmDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmDeleteUser">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        return {
            formLabelWidth: '120px',
            addForm: {
                name: '',
                account: '',
                contact: '',
                password: ''
            },
            editForm: {
                id: '',
                name: '',
                account: '',
                contact: '',
                password: ''
            },
            editDialogFormVisible: false,
            addDialogFormVisible: false,
            deleteConfirmDialogVisible: false,
            searchKeyword: '',
            // 当前要删除的用户
            currentUserToDelete: null,
            // 当前要修改的用户
            currentUserToEdit: null,
            // 用户数据表格
            tableData: [],
            // 管理员数据表格
            adminTableData: [],
            currentTableData: [],
            isVisitorActive: true,
            isAdminActive: false,
            // 分页相关数据
            currentPage: 1,
            pageSize: 10
        }
    },
    computed: {
        filteredTableData() {
            const keyword = this.searchKeyword.trim().toLowerCase();
            if (!keyword) {
                return this.currentTableData;
            }
            return this.currentTableData.filter(item => item.name.toLowerCase().includes(keyword));
        },
        // 分页后的表格数据
        paginatedTableData() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = this.currentPage * this.pageSize;
            return this.filteredTableData.slice(start, end);
        }
    },
    created() {
        this.init();
    },
    methods: {
        init() {
            const res = {
                data: [
                    {
                        id: '1',
                        account: '123456',
                        contact: '123456789',
                        date: '2016-05-02',
                        name: '王小虎',
                        password: '123456',
                        identity: 'customer'
                    }, {
                        id: '2',
                        account: '123456',
                        contact: '123456789',
                        date: '2016-05-02',
                        name: '王小虎',
                        password: '123456',
                        identity: 'customer'
                    }, {
                        id: '3',
                        account: '123456',
                        contact: '123456789',
                        date: '2016-05-02',
                        name: '王小虎',
                        password: '123456',
                        identity: 'customer'
                    }, {
                        id: '4',
                        account: '123456',
                        contact: '123456789',
                        date: '2016-05-02',
                        name: '王小虎',
                        password: '123456',
                        identity: 'customer'
                    }
                ]
            };
            const resAdmin = {
                data: [
                    {
                        id: '1',
                        account: '123456',
                        contact: '123456789',
                        date: '2016-05-02',
                        name: '张三',
                        password: '123456',
                        identity: 'admin'
                    },
                    {
                        id: '2',
                        account: '123456',
                        contact: '123456789',
                        date: '2016-05-02',
                        name: '李四',
                        password: '123456',
                        identity: 'admin'
                    },
                    {
                        id: '3',
                        account: '123456',
                        contact: '123456789',
                        date: '2016-05-02',
                        name: '小明',
                        password: '123456',
                        identity: 'admin'
                    },
                    {
                        id: '4',
                        account: '123456',
                        contact: '123456789',
                        date: '2016-05-02',
                        name: '小红',
                        password: '123456',
                        identity: 'admin'
                    },
                    {
                        id: '5',
                        account: '123456',
                        contact: '123456789',
                        date: '2016-05-02',
                        name: '小蓝',
                        password: '123456',
                        identity: 'admin'
                    }
                ]
            };
            this.adminTableData = resAdmin.data;
            this.tableData = res.data;
            this.currentTableData = this.tableData; // 初始化时显示游客用户数据
        },
        showVisitorData() {
            this.currentTableData = this.tableData;
            this.isVisitorActive = true;
            this.isAdminActive = false;
            this.currentPage = 1;
        },
        showAdminData() {
            this.currentTableData = this.adminTableData;
            this.isVisitorActive = false;
            this.isAdminActive = true;
            this.currentPage = 1;
        },
        searchUsers() {
            // 搜索输入框失去焦点时触发搜索
            this.$forceUpdate();
        },
        // 新增用户
        addUser() {
            if (!this.addForm.name || !this.addForm.account) {
                this.$message.error('用户姓名和登录账号不能为空');
                return;
            }
            const newUserId = 'new_' + Date.now() + '_' + Math.floor(Math.random() * 1000);
            const newUser = {
                id: newUserId,
                name: this.addForm.name,
                account: this.addForm.account,
                password: this.addForm.password,
                contact: this.addForm.contact,
                date: new Date().toISOString().split('T')[0],
                identity: this.isVisitorActive ? 'customer' : 'admin'
            };
            if (this.isVisitorActive) {
                this.tableData.push(newUser);
            } else {
                this.adminTableData.push(newUser);
            }
            this.currentTableData = this.isVisitorActive ? this.tableData : this.adminTableData;
            this.addDialogFormVisible = false;
            this.$message.success("添加成功");
            this.addForm.name = '';
            this.addForm.account = '';
            this.addForm.password = '';
            this.addForm.contact = '';
            this.currentPage = 1;
        },
        // 取消新增用户
        cancelAddUser() {
            this.addDialogFormVisible = false;
            this.addForm.name = '';
            this.addForm.account = '';
            this.addForm.password = '';
            this.addForm.contact = '';
        },
        // 修改用户
        editUser(row) {
            this.currentUserToEdit = row;
            this.editForm = { ...row };
            this.editDialogFormVisible = true;
        },
        // 保存修改的用户信息
        saveEditUser() {
            if (!this.currentUserToEdit) return;
            if (!this.editForm.name || !this.editForm.account) {
                this.$message.error('用户姓名和登录账号不能为空');
                return;
            }
            if (this.isVisitorActive) {
                const index = this.tableData.findIndex(item => item.id === this.currentUserToEdit.id);
                if (index !== -1) {
                    this.tableData[index] = this.editForm;
                }
            } else {
                const index = this.adminTableData.findIndex(item => item.id === this.currentUserToEdit.id);
                if (index !== -1) {
                    this.adminTableData[index] = this.editForm;
                }
            }
            this.currentTableData = this.isVisitorActive ? this.tableData : this.adminTableData;
            this.editDialogFormVisible = false;
            this.$message.success("修改成功");
            this.currentUserToEdit = null;
            this.editForm = {
                id: '',
                name: '',
                account: '',
                contact: '',
                password: ''
            };
        },
        // 删除用户
        deleteUser(row) {
            this.currentUserToDelete = row;
            this.deleteConfirmDialogVisible = true;
        },
        // 确认删除用户
        confirmDeleteUser() {
            if (!this.currentUserToDelete) return;
            if (this.isVisitorActive) {
                const index = this.tableData.findIndex(item => item.id === this.currentUserToDelete.id);
                if (index !== -1) {
                    this.tableData.splice(index, 1);
                }
            } else {
                const index = this.adminTableData.findIndex(item => item.id === this.currentUserToDelete.id);
                if (index !== -1) {
                    this.adminTableData.splice(index, 1);
                }
            }
            this.currentTableData = this.isVisitorActive ? this.tableData : this.adminTableData;
            this.deleteConfirmDialogVisible = false;
            this.$message.success("删除成功");
            this.currentUserToDelete = null;
            // 如果删除后当前页没有数据了，跳转到上一页
            if (this.paginatedTableData.length === 0 && this.currentPage > 1) {
                this.currentPage--;
            }
        },
        // 每页条数改变时触发
        handleSizeChange(val) {
            this.pageSize = val;
            this.currentPage = 1;
        },
        // 当前页改变时触发
        handleCurrentChange(val) {
            this.currentPage = val;
        }
    }
}
</script>
<style scoped>
.header-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.search-input {
    width: 203px;
}

.container-main {
    padding: 32px;
}

.header-search {
    display: flex;
}

.search-button {
    position: relative;
    left: -100px;
}

.block {
    display: flex;
    justify-content: center;
}

.active {
    background-color: #409eff;
    color: white;
}

/* 分页样式 */
.el-pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>